<!--
  * CEP规则管理
  *
  * @Author:    chenyuqiang
  * @Date:      2025-08-21 22:46:37
  * @Copyright  1
-->
<template>
  <div class="cep-container">
    <a-card size="small" :bordered="false" :hoverable="true">
      <!-- 查询表单 -->
      <a-form class="smart-query-form">
        <a-row class="smart-query-form-row" :gutter="16">
          <a-col :span="6">
            <a-form-item label="规则名称">
              <a-input
                v-model:value.trim="queryForm.ruleName"
                placeholder="请输入规则名称"
                allow-clear
              />
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="规则编码">
              <a-input
                v-model:value.trim="queryForm.ruleCode"
                placeholder="请输入规则编码"
                allow-clear
              />
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="规则类型">
              <a-select
                v-model:value="queryForm.ruleType"
                placeholder="请选择规则类型"
                allow-clear
              >
                <a-select-option value="SIMPLE">普通规则</a-select-option>
                <a-select-option value="COMPLEX">关联规则</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="规则状态">
              <a-select
                v-model:value="queryForm.status"
                placeholder="请选择规则状态"
                allow-clear
              >
                <a-select-option value="ACTIVE">激活</a-select-option>
                <a-select-option value="INACTIVE">停用</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        
        <a-row class="smart-query-form-row">
          <a-form-item class="smart-query-form-item">
            <a-button type="primary" @click="onSearch">
              <template #icon>
                <SearchOutlined />
              </template>
              查询
            </a-button>
            <a-button @click="resetQuery" class="smart-margin-left10">
              <template #icon>
                <ReloadOutlined />
              </template>
              重置
            </a-button>
          </a-form-item>
        </a-row>
      </a-form>

      <!-- 表格操作行 -->
      <a-row class="smart-table-btn-block">
        <div class="smart-table-operate-block">
          <a-button @click="showForm" type="primary" size="small">
            <template #icon>
              <PlusOutlined />
            </template>
            新建规则
          </a-button>
          <a-button 
            @click="confirmBatchDelete" 
            type="primary" 
            danger 
            size="small" 
            :disabled="selectedRowKeyList.length === 0"
          >
            <template #icon>
              <DeleteOutlined />
            </template>
            批量删除
          </a-button>
        </div>
        <div class="smart-table-setting-block">
          <TableOperator v-model="columns" :tableId="TABLE_ID_CONST.BUSINESS.CEP" :refresh="queryData" />
        </div>
      </a-row>

      <!-- 数据表格 -->
      <a-table
        size="small"
        :scroll="{ x: 1400, y: 600 }"
        :dataSource="tableData"
        :columns="columns"
        rowKey="id"
        bordered
        :loading="tableLoading"
        :pagination="false"
        :row-selection="{ selectedRowKeys: selectedRowKeyList, onChange: onSelectChange }"
      >
        <template #bodyCell="{ text, record, column }">
          <template v-if="column.dataIndex === 'status'">
            <a-tag :color="text === 'ACTIVE' ? 'processing' : 'error'">
              {{ text === 'ACTIVE' ? '激活' : '停用' }}
            </a-tag>
          </template>
          
          <template v-else-if="column.dataIndex === 'ruleType'">
            <a-tag :color="getRuleTypeColor(text)">
              {{ text }}
            </a-tag>
          </template>

          <template v-else-if="column.dataIndex === 'action'">
            <div class="smart-table-operate">
              <a-button @click="showForm(record)" type="link" size="small">
                <template #icon>
                  <EditOutlined />
                </template>
                编辑
              </a-button>
              <a-button @click="onDelete(record)" danger type="link" size="small">
                <template #icon>
                  <DeleteOutlined />
                </template>
                删除
              </a-button>
            </div>
          </template>
        </template>
      </a-table>

      <!-- 分页 -->
      <div class="smart-query-table-page">
        <a-pagination
          showSizeChanger
          showQuickJumper
          show-less-items
          :pageSizeOptions="PAGE_SIZE_OPTIONS"
          :defaultPageSize="queryForm.pageSize"
          v-model:current="queryForm.pageNum"
          v-model:pageSize="queryForm.pageSize"
          :total="total"
          @change="queryData"
          @showSizeChange="queryData"
          :show-total="(total) => `共${total}条`"
        />
      </div>

      <!-- CEP规则表单 -->
      <CepForm ref="formRef" @reloadList="queryData" />
    </a-card>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted } from 'vue';
import { message, Modal } from 'ant-design-vue';
import { 
  SearchOutlined, 
  ReloadOutlined, 
  PlusOutlined, 
  DeleteOutlined,
  EditOutlined
} from '@ant-design/icons-vue';
import { SmartLoading } from '/@/components/framework/smart-loading';
import { cepApi } from '/@/api/business/cep/cep-api';
import { PAGE_SIZE_OPTIONS } from '/@/constants/common-const';
import { smartSentry } from '/@/lib/smart-sentry';
import TableOperator from '/@/components/support/table-operator/index.vue';
import CepForm from './cep-form.vue';
import { TABLE_ID_CONST } from '/@/constants/support/table-id-const';

// ---------------------------- 表格列定义 ----------------------------
const columns = ref([
  {
    title: '规则ID',
    dataIndex: 'id',
    width: 80,
    ellipsis: true,
  },
  {
    title: '规则名称',
    dataIndex: 'ruleName',
    width: 150,
    ellipsis: true,
  },
  {
    title: '规则编码',
    dataIndex: 'ruleCode',
    width: 120,
    ellipsis: true,
  },
  {
    title: '规则描述',
    dataIndex: 'ruleDescription',
    width: 200,
    ellipsis: true,
  },
  {
    title: '规则类型',
    dataIndex: 'ruleType',
    width: 100,
  },
  {
    title: '规则状态',
    dataIndex: 'status',
    width: 100,
  },
  {
    title: '规则版本',
    dataIndex: 'version',
    width: 100,
    ellipsis: true,
  },
  {
    title: '创建时间',
    dataIndex: 'createdTime',
    width: 160,
    ellipsis: true,
  },
  {
    title: '更新时间',
    dataIndex: 'updatedTime',
    width: 160,
    ellipsis: true,
  },
  {
    title: '创建人',
    dataIndex: 'createdBy',
    width: 100,
    ellipsis: true,
  },
  {
    title: '更新人',
    dataIndex: 'updatedBy',
    width: 100,
    ellipsis: true,
  },
  {
    title: '操作',
    dataIndex: 'action',
    fixed: 'right',
    width: 120,
  },
]);

// ---------------------------- 查询表单和方法 ----------------------------
const queryFormState = {
  pageNum: 1,
  pageSize: 10,
  ruleName: '',
  ruleCode: '',
  ruleType: undefined,
  status: undefined,
};

const queryForm = reactive({ ...queryFormState });
const tableLoading = ref(false);
const tableData = ref([]);
const total = ref(0);

// 重置查询条件
function resetQuery() {
  let pageSize = queryForm.pageSize;
  Object.assign(queryForm, queryFormState);
  queryForm.pageSize = pageSize;
  queryData();
}

// 搜索
function onSearch() {
  queryForm.pageNum = 1;
  queryData();
}

// 查询数据
async function queryData() {
  tableLoading.value = true;
  try {
    let queryResult = await cepApi.queryPage(queryForm);
    tableData.value = queryResult.data.list;
    total.value = queryResult.data.total;
  } catch (e) {
    smartSentry.captureError(e);
    message.error('查询数据失败');
  } finally {
    tableLoading.value = false;
  }
}

onMounted(queryData);

// ---------------------------- 添加/修改 ----------------------------
const formRef = ref();

function showForm(data) {
  formRef.value.show(data);
}

// ---------------------------- 删除操作 ----------------------------
function onDelete(data) {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除规则"${data.ruleName}"吗？`,
    okText: '删除',
    okType: 'danger',
    onOk() {
      requestDelete(data);
    },
    cancelText: '取消',
  });
}

async function requestDelete(data) {
  SmartLoading.show();
  try {
    await cepApi.delete(data.id);
    message.success('删除成功');
    queryData();
  } catch (e) {
    smartSentry.captureError(e);
    message.error('删除失败');
  } finally {
    SmartLoading.hide();
  }
}

// ---------------------------- 批量删除 ----------------------------
const selectedRowKeyList = ref([]);

function onSelectChange(selectedRowKeys) {
  selectedRowKeyList.value = selectedRowKeys;
}

function confirmBatchDelete() {
  if (selectedRowKeyList.value.length === 0) {
    message.warning('请选择要删除的规则');
    return;
  }
  
  Modal.confirm({
    title: '确认批量删除',
    content: `确定要删除选中的 ${selectedRowKeyList.value.length} 条规则吗？`,
    okText: '删除',
    okType: 'danger',
    onOk() {
      requestBatchDelete();
    },
    cancelText: '取消',
  });
}

async function requestBatchDelete() {
  try {
    SmartLoading.show();
    await cepApi.batchDelete(selectedRowKeyList.value);
    message.success('批量删除成功');
    selectedRowKeyList.value = [];
    queryData();
  } catch (e) {
    smartSentry.captureError(e);
    message.error('批量删除失败');
  } finally {
    SmartLoading.hide();
  }
}

// ---------------------------- 工具函数 ----------------------------
function getRuleTypeColor(ruleType) {
  const colorMap = {
    'CEP': 'blue',
    'RULE': 'green'
  };
  return colorMap[ruleType] || 'default';
}
</script>

<style scoped lang="less">
.cep-container {
  padding: 16px;
  
  .smart-query-form {
    margin-bottom: 16px;
    
    .smart-query-form-row {
      margin-bottom: 16px;
      
      &:last-child {
        margin-bottom: 0;
      }
    }
  }
  
  .smart-table-btn-block {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    
    .smart-table-operate-block {
      .ant-btn {
        margin-right: 8px;
      }
    }
  }
  
  .smart-table-operate {
    display: flex;
    gap: 8px;
  }
  
  .smart-query-table-page {
    margin-top: 16px;
    text-align: right;
  }
}
</style>
